using RuiXinCoffee.Utils;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace RuiXinCoffee.UI
{
    public class BaseForm : Form
    {
        private Form _parentForm;
        private float _scaleFactor = 1.0f;
        private Size _originalSize;
        private Dictionary<Control, Rectangle> _originalControlBounds;
        private Dictionary<Control, Font> _originalFonts;
        
        public BaseForm()
        {
            _originalControlBounds = new Dictionary<Control, Rectangle>();
            _originalFonts = new Dictionary<Control, Font>();
            
            //窗体加载时记录原始大小
            this.Load += (sender, e) =>
            {
                _originalSize = this.Size;
                SaveOriginalControlProperties(this);
            };
            
            //调整大小时缩放控件
            this.SizeChanged += (sender, e) =>
            {
                if (_originalSize.Width == 0 || _originalSize.Height == 0) return;
                
                _scaleFactor = Math.Min(
                    (float)this.Width / _originalSize.Width,
                    (float)this.Height / _originalSize.Height
                );
                
                ScaleControls(this, _scaleFactor);
            };
            
            //添加全局异常处理
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }
        
        //全局UI线程异常处理
        private void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }
        
        //全局非UI线程异常处理
        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception);
        }
        
        //统一处理异常的方法
        protected virtual void HandleException(Exception ex)
        {
            if (ex == null) return;
            
            string message = "发生错误";
            string title = "系统错误";
            
            if (ex is RuiXinException ruiXinEx)
            {
                //处理自定义异常
                message = ruiXinEx.Message;
                
                if (ruiXinEx is DatabaseException)
                {
                    title = "数据库错误";
                }
                else if (ruiXinEx is ImageProcessException)
                {
                    title = "图片处理错误";
                }
                else if (ruiXinEx is BusinessException)
                {
                    title = "业务逻辑错误";
                }
                else if (ruiXinEx is UserOperationException)
                {
                    title = "操作错误";
                }
            }
            else
            {
                //处理系统异常
                message = $"发生系统错误: {ex.Message}";
            }
            
            MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        
        //设置父窗体，用于位置绑定
        public void SetParentForm(Form parentForm)
        {
            _parentForm = parentForm;
            if (_parentForm != null)
            {
                //将窗体显示在父窗体中心
                this.StartPosition = FormStartPosition.Manual;
                PositionFormRelativeToParent();
                
                //监听父窗体位置变化
                _parentForm.LocationChanged += (sender, e) => PositionFormRelativeToParent();
            }
        }
        
        //定位窗体相对于父窗体
        private void PositionFormRelativeToParent()
        {
            if (_parentForm == null || _parentForm.IsDisposed) return;
            
            int x = _parentForm.Left + (_parentForm.Width - this.Width) / 2;
            int y = _parentForm.Top + (_parentForm.Height - this.Height) / 2;
            
            this.Location = new Point(x, y);
        }
        
        //保存控件原始属性
        private void SaveOriginalControlProperties(Control control)
        {
            foreach (Control c in control.Controls)
            {
                _originalControlBounds[c] = new Rectangle(c.Left, c.Top, c.Width, c.Height);
                if (c.Font != null)
                {
                    _originalFonts[c] = c.Font;
                }
                
                if (c.Controls.Count > 0)
                {
                    SaveOriginalControlProperties(c);
                }
            }
        }
        
        //缩放控件
        private void ScaleControls(Control container, float factor)
        {
            foreach (Control c in container.Controls)
            {
                if (_originalControlBounds.TryGetValue(c, out Rectangle originalBounds))
                {
                    c.Left = (int)(originalBounds.Left * factor);
                    c.Top = (int)(originalBounds.Top * factor);
                    c.Width = (int)(originalBounds.Width * factor);
                    c.Height = (int)(originalBounds.Height * factor);
                }
                
                if (_originalFonts.TryGetValue(c, out Font originalFont))
                {
                    float newSize = originalFont.Size * factor;
                    c.Font = new Font(originalFont.FontFamily, newSize, originalFont.Style);
                }
                
                if (c.Controls.Count > 0)
                {
                    ScaleControls(c, factor);
                }
            }
        }
        
        //显示模态对话框并绑定到父窗体位置
        public DialogResult ShowDialogWithBinding(Form parentForm)
        {
            SetParentForm(parentForm);
            return this.ShowDialog();
        }
        
        //显示非模态窗口并绑定到父窗体位置
        public void ShowWithBinding(Form parentForm)
        {
            SetParentForm(parentForm);
            this.Show();
        }
        
        //重写Dispose方法，解除事件订阅
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Application.ThreadException -= Application_ThreadException;
                AppDomain.CurrentDomain.UnhandledException -= CurrentDomain_UnhandledException;
            }
            base.Dispose(disposing);
        }
        
        // 设计器支持 - 提供一个空的默认构造函数
        static BaseForm()
        {
            // 用于确保设计器可以正确加载此类
        }
    }
} 